const plyfeaModel = require('../models/playerfeatures.js')

class PlayerfeatureCtrl {

    async list() {
        let lst = await plyfeaModel.find();//.sort('id');
        return lst.map(m=>m.toJSON());
    }

    async create(plyfeaData) {
        let plyfea = new plyfeaModel(plyfeaData);
        plyfea = await plyfea.save();
        return plyfea.toJSON();
    }

    async retrieve(id) {
        let plyfea = await plyfeaModel.findById(id);
        return plyfea?plyfea.toJSON(): null;
    }

    async upsert(id, plyfeaData) {
        plyfeaData.id = id;
        let plyfea = await plyfeaModel.upsert(id, plyfeaData);
        return plyfea.toJSON();
    }
    async removeById(id) {
        await plyfeaModel.removeById(id);
        return 1;
    }
    async find(filter)
    {
        let r = await plyfeaModel.find(filter);
        return r.map(e=>e.toJSON());
    }
    async distributionStats(pid) {
        let distb = plyfeaModel.aggregate();
        console.log(distb)
        let distribution = await distb.group({_id:"$passFrom", froms: {$sum:1}});//, fxg:{$avg:"$startX"}, fyg:{$avg:"$startY"}});
        let to = eventModel.aggregate([{$match:{matchId:mid, playerId:pid, eventId:8}}]);
        let togroup = await to.group({_id:"$passTo", tos: {$sum:1}})//, txg:{$avg:"$endX"}, tyg:{$avg:"$endY"}});//moogoose 聚合:累加+平均

        //console.log(r)

        let ret = {};
        for( let fg of fromgroup){
            if (fg._id != 'none'){
                let playerId = fg._id;
                if(!Object.hasOwnProperty.call(ret, playerId)){//ret无playerId,tui
                    ret[playerId] = { playerId, froms: fg.froms, tos: 0}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret[playerId].froms = fg.froms; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }

        for( let tg of togroup) {//另外de聚合
            if (tg._id != 'none'){    
                let playerId = tg._id;
                if(!Object.hasOwnProperty.call(ret, playerId)){
                    ret[playerId] = { playerId, froms: 0, tos: tg.tos}//, fxg: 0, fyg: 0, txg: tg.txg, tyg: tg.tyg};
                }else{
                    ret[playerId].tos = tg.tos;
                    //ret[playerId].txg = tg.txg;
                    //ret[playerId].tyg = tg.tyg; 
                }
            }
            else{continue;}
        }
        return ret
        /**let result=[];
        for(let d of ret) { result.push(d.toJSON())}
        return result*/
    }
}

module.exports = new PlayerfeatureCtrl();